//
//  ViewController.m
//  疯狂猜图1
//
//  Created by app33 on 15/5/16.
//  Copyright (c) 2015年 app33. All rights reserved.
//

#import "ViewController.h"
#import "Question.h"
@interface ViewController ()
//提示
- (IBAction)tip;
//大图
- (IBAction)bigImg;
//帮助
- (IBAction)help;
//下一题
- (IBAction)nextQuestion;
//上一题
- (IBAction)previousQuestion;
//单击图像
- (IBAction)iconClick;

@property (weak, nonatomic) IBOutlet UIButton *scoreBtn;
//存放正确答案按钮的view
@property (weak, nonatomic) IBOutlet UIView *answerView;
@property (weak, nonatomic) IBOutlet UIView *optionView;
//序号
@property (weak, nonatomic) IBOutlet UILabel *noLabel;
//标题
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
// 头像(图标)
@property (weak, nonatomic) IBOutlet UIButton *iconBtn;
//下一题按钮
@property (weak, nonatomic) IBOutlet UIButton *nextQuestionBtn;
//上一题按钮
@property (weak, nonatomic) IBOutlet UIButton *previousQuestionBtn;
//遮盖
@property (nonatomic, weak) UIButton *cover;
//所有的题目
@property (nonatomic, strong) NSArray *questions;
//当前是第几题(当前题目的序号)
@property (nonatomic, assign) int index;
//最大题号
@property(nonatomic,assign)int maxIndex;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化序号值
    _index=-1;
    _maxIndex=0;
    //进入下一题
    [self nextQuestion];
    
}
//懒调用
-(NSArray *)questions
{
    //如果数据为空就加载
   if(_questions==nil)
   {
       NSString *path=[[NSBundle mainBundle]pathForResource:@"questions" ofType:@"plist"];
       NSArray *array=[NSArray arrayWithContentsOfFile:path];
       NSMutableArray *mutableArray=[NSMutableArray array];
       for (NSDictionary *dict in array) {
           Question *question=[Question QuestiomWithDict:dict];
           [mutableArray addObject:question];
           _questions=mutableArray;
       }
   }
    return _questions;
}
//添加分数
- (Boolean)addScore:(int)Score
{
    //将现有的分数取出来与要添加的分数相加
    int score=[self.scoreBtn.currentTitle intValue];
    Boolean add=NO;
    if (score+Score>=0&&_maxIndex==self.index) {
        score+=Score;
        add=YES;
     [self.scoreBtn setTitle:[NSString stringWithFormat:@"%d",score] forState:UIControlStateNormal];
    }
    else
    {
        add=YES;
//        UIAlertView *alter=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"你的余额不足，请充值！" delegate:self cancelButtonTitle:@"退出" otherButtonTitles:@"确定", nil];
//        [alter show];
    }
    return add;
}
// 提示
- (IBAction)tip {
    
    int i=0;
    for (UIButton *button in self.answerView.subviews) {
        if (button.currentTitle==nil) {
            break;
        }
        else{
            i++;
        }
    }
    Question *question=_questions[self.index];
    NSString *string=question.answer;
    //减去相应的分数
    if (i<=string.length-1&&[self addScore:-1000]) {
        NSString *str=[string substringWithRange:NSMakeRange(i, 1)];
        //将选择区域的按钮遍历一遍寻找与答案第一个字符相等的选项将其隐藏
        for (UIButton *button in self.optionView.subviews) {
            if ([button.currentTitle isEqualToString:str]) {
                [self optionClick:button];
                break;
            }
        }
    }
}
// 下一题
- (IBAction)nextQuestion {
    //判断是否达到最后一题
    if (self.index==(self.questions.count-1)) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"恭喜" message:@"成功过关" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        return;
    }
    _index++;
    if (_index>_maxIndex) {
        _maxIndex=_index;
    }
    Question *question=_questions[self.index];
    [self settingData:question];
    [self addAnswerBtn:question];
    [self addOptionBtn:question];
}
//设置控件的数据
- (void)settingData:(Question *)question
{
    //设置关数标签
    self.noLabel.text=[NSString stringWithFormat:@"%i/%i",1+_index,(int)self.questions.count];
    //设置提示信息
    self.titleLabel.text=question.title;
    //设置头像
    [self.iconBtn setImage:[UIImage imageNamed:question.icon] forState:UIControlStateNormal];
    //设置下一题按钮的状态
    self.nextQuestionBtn.enabled=(self.index<self.maxIndex);
    //设置上一题按钮的状态
    self.previousQuestionBtn.enabled=!(self.index<1);
}

//添加待选项
- (void)addOptionBtn:(Question *)question
{
    self.optionView.userInteractionEnabled=YES;
    //移除所有子视图
    [self.optionView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    //获得所有选项的个数
    NSInteger count=question.options.count;
    for(int i=0;i<count;i++)
    {
        //构造按钮
        UIButton *button=[[UIButton alloc]init];
        //设置按钮背景图片
        [button setBackgroundImage:[UIImage imageNamed:@"btn_answer"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"btn_answer_highlight"] forState:UIControlStateHighlighted];
        //设置按钮的位置
        CGFloat viewW=self.view.frame.size.width;
        CGFloat rolMax=7;
        CGFloat margin=10;
        CGFloat optionW=(viewW-margin*(rolMax+1))/(rolMax*1.0);
        CGFloat optionH=optionW;
        CGFloat optionX=margin+(optionW+margin)*(i%7);
        CGFloat optionY=(margin+optionH)*(i/7);
        button.frame=CGRectMake(optionX, optionY, optionW, optionH);
        //获取对应的选项文字
        NSString *string=question.options[i];
        //将获得的文字设置为按钮标题
        [button setTitle:string forState:UIControlStateNormal];
        //设置按钮的标题的颜色为黑色
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        //将按钮添加到选择区域中去
        [self.optionView addSubview:button];
        //为按钮添加单击事件
        [button addTarget:self action:@selector(optionClick:) forControlEvents:UIControlEventTouchUpInside];
    }
}
// 监听待选按钮的点击
- (void)optionClick:(UIButton *)optionBtn
{
    //将选择区域的按钮隐藏
    optionBtn.hidden=YES;
    //在答案区域查找空白按钮将其标题设置为选择区域按钮的标题
    for (UIButton *button in self.answerView.subviews) {
        NSString *btnStr=[button titleForState:UIControlStateNormal];
        if (btnStr.length==0) {
            NSString *optionStr=[optionBtn titleForState:UIControlStateNormal];
            [button setTitle:optionStr forState:UIControlStateNormal];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            break;
        }
    }
    //判断答案区域是否都有标题
    BOOL full=YES;
    NSMutableString *mutableStr=[NSMutableString string];
    for (UIButton *button in self.answerView.subviews) {
        NSString *string=[button titleForState:UIControlStateNormal];
        if (string.length==0) {
            full=NO;
            break;
        }
        //如果有标题将其标题拼串
        if (string) {
            [mutableStr appendString:string];
        }
    }
    if (full) {
        //如果答案区域的按钮都有标题，那么使选择区域的交互不可用
        self.optionView.userInteractionEnabled=NO;
        Question *question=self.questions[self.index];
        //判断拼的字符串是否与答案相同
        if ([mutableStr isEqualToString:question.answer]) {
            //如果相同将按钮的字体颜色设置为蓝色
            for (UIButton *button in self.answerView.subviews) {
                [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            }
            //通过一关加800分
            if (_index==_maxIndex) {
               [self addScore:800];
            }
            //0.5秒后调用下一题方法
            [self performSelector:@selector(nextQuestion) withObject:nil afterDelay:0.5];
        }
        else
        {
            //如果不是正确答案将字体颜色设置为红色
            for (UIButton *button in self.answerView.subviews) {
                [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            }
        }

    }
    
}
// 添加正确答案
- (void)addAnswerBtn:(Question *)question
{
    //移除所有子视图
    [self.answerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    //拿到题目的个数
    NSInteger length=question.answer.length;
    for(int i=0;i<length;i++)
    {
        //构造按钮视图
    UIButton *button=[[UIButton alloc]init];
        //设置按钮的背景图片
        [button setBackgroundImage:[UIImage imageNamed:@"btn_answer"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"btn_answer_highlight"] forState:UIControlStateHighlighted];
        //设置按钮的位置
    CGFloat viewW=self.view.frame.size.width;
    CGFloat margin=10;
    CGFloat answerW=35;
    CGFloat answerH=35;
    CGFloat leftMargin=(viewW-margin*(length-1)-answerW*length)*0.5;
    button.frame=CGRectMake(leftMargin+(answerW+margin)*i, 0, answerW, answerH);
//        将按钮添加到答案视图区域
        [self.answerView addSubview:button];
    [button addTarget:self action:@selector(answerClick:) forControlEvents:UIControlEventTouchUpInside];
    }
}
// 监听答案按钮的点击
- (void)answerClick:(UIButton *)answerBtn
{
    self.optionView.userInteractionEnabled=YES;
    NSString *string=[answerBtn titleForState:UIControlStateNormal];
    for (UIButton *button  in self.optionView.subviews) {
        if ([button.currentTitle isEqualToString:string]&&button.isHidden) {
            [button setHidden:NO];
            break;
        }
    }
    [answerBtn setTitle:nil forState:UIControlStateNormal];
    for (UIButton *button in self.answerView.subviews) {
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
}
//点击头像
- (IBAction)iconClick {
    //如果遮盖视图为空调用大图模式否则调用小图模式
    if (self.cover==nil) {
        [self bigImg];
    }
    else
    {
    [self smallImg];
    }
    
}
//大图
- (IBAction)bigImg {
    //构造遮盖按钮
    UIButton *cover=[[UIButton alloc]init];
    //使遮盖视图和屏幕大小一样
    cover.frame=self.view.bounds;
    //将其背景颜色设置为黑色
    [cover setBackgroundColor:[UIColor blackColor]];
    //透明度设置为0
    cover.alpha=0.0;
    //将遮盖视图赋值给全局变量
    self.cover=cover;
    //将遮盖视图添加到当前视图
    [self.view addSubview:cover];
    //为遮盖视图添加事件单击时变小
    [cover addTarget:self action:@selector(smallImg) forControlEvents:UIControlEventTouchUpInside];
    //将头像视图按钮移到视图的最上面
    [self.view bringSubviewToFront:self.iconBtn];
    //设置遮盖视图的透明度
    cover.alpha=0.8;
    //设置仿射变换
    _iconBtn.transform=CGAffineTransformScale(_iconBtn.transform, 2, 2);
}
//小图
- (void)smallImg
{
    //设置遮盖视图的透明度
    self.cover.alpha=0.0;
    //设置仿射变换
    _iconBtn.transform=CGAffineTransformScale(_iconBtn.transform, 0.5,0.5);
    //结束时把遮盖视图从父视图中移除
    [self.cover removeFromSuperview];
    //将遮盖视图赋值为空
    self.cover=nil;
}
//帮助
- (IBAction)help {
    UIAlertView *alter=[[UIAlertView alloc]initWithTitle:@"帮助" message:@"暂无此功能" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alter show];
    
}
- (IBAction)previousQuestion {
    if (self.index>0) {
        _index=_index-2;
        [self nextQuestion];
    }
}
@end
